<template>
  <div class="footer flex items-center w-full bg-F8F8F8 p-20px box-border relative">
    <div class="tools h-full flex items-center pr-10px">
      <img
        class="item mr-10px"
        src="static/icons/mic.png"
        mode=""
        @click="changeMessageType"
        v-show="false && messageType === MessageType.TEXT"
      />
      <img
        class="item mr-10px"
        src="static/icons/keyboard.png"
        mode=""
        @click="changeMessageType"
        v-show="messageType === MessageType.VOICE"
      />
      <el-popover
        style="font-size: 0"
        placement="top"
        width="100"
        trigger="manual"
        v-model="isShowVoipPopover"
      >
        <div class="flex flex-col items-center justify-between" style="height: 1.05rem">
          <CustomButton
            class="block"
            style="width: 1.4rem; height: 0.47rem"
            @click="toCall('voice')"
          >
            语音通话
          </CustomButton>
          <CustomButton
            class="block"
            style="width: 1.4rem; height: 0.47rem"
            @click="toCall('video')"
          >
            视频通话
          </CustomButton>
        </div>
        <img
          v-show='userRole === "家长"'
          class="item mr-10px"
          src="static/icons/phone.png"
          slot="reference"
          @click.stop="isShowVoipPopover = !isShowVoipPopover"
        />
      </el-popover>
    </div>

    <div class="flex w-full h-full" v-show="messageType === MessageType.TEXT">
      <input
        id="input"
        v-model="draft.text"
        class="input w-full h-full bg-white p-12px box-border"
        placeholder=""
        type="text"
      />
      <div
        class="btn-confirm h-full bg-51C3FF flex-center text-white ml-10px"
        @click="sendTextMessage"
      >
        发送
      </div>
    </div>
    <div
      class="input flex w-full h-full bg-51C3FF-20 text-51C3FF p-12px box-border flex-center"
      v-show="messageType === MessageType.VOICE"
      @click="sendVoiceMessage"
      @touchstart.prevent="startRecorder"
      @touchend.prevent="endRecorder"
    >
      {{ isRecording ? '松开发送' : '按住说话' }}
    </div>

    <mumu-recorder
      ref="recorderRef"
      @success="handlerH5RecorderSuccess"
      @error="handlerH5RecorderError"
    ></mumu-recorder>

    <div class="dialog-recording absolute" v-show="isShowRecordingDialog">
      <div class="wrap flex flex-col items-center">
        <img class="icon-recording" src="static/icons/recording.png" mode="" />
        <img class="icon-cancel mt-10px" src="static/icons/cancel.png" mode="" />
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters } from 'vuex'
import IM from '@/im'
import { getStudentCallManage } from '@/api/contact'
import MumuRecorder from './mumu-recorder.vue'
import CustomButton from '@/components/button'

const { MessageType } = IM

export default {
  components: {
    MumuRecorder,
    CustomButton
  },
  props: {
    currentContact: {
      type: Object,
      default: () => {}
    },
    isShowRecordingDialog: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      appDom: document.getElementById('app'),
      MessageType,
      messageType: MessageType.TEXT,
      inputStatus: '',
      isRecording: false,
      recorderManager: {
        instance: undefined,
        startTime: undefined,
        endTime: undefined
      },
      isShowVoipPopover: false,
      draft: {
        text: ''
      }
    }
  },
  computed: {
    ...mapGetters(['serialNo']),
    ...mapState(['im']),
    studentInfo() {
      const { userId, users } = this.im
      return users.find((u) => u.userId === userId)
    },
    userRole(){
      if(this.currentContact){
        let userId = this.currentContact.userId
        let roleName = userId.split(':')[0]
        switch (roleName) {
          case 'user':
            return '老师'
          case 'parentUser':
            return '家长'
          default:
            return '家长'
        }
      }
    },
  },
  beforeCreate() {
    // 初始化小程序硬件框架
    if (window.android) {
      // WMPF 启动微信小程序回调
      window.android_call['wmpf_onLaunchMiniProgram'] = (res) => {
        // console.log('WMPF onLaunchMiniProgram =>', res)
      }
    }
  },
  mounted() {
    const input = document.getElementById('input')

    input.addEventListener('focus', () => {
      this.inputStatus = 'focus'
    })

    input.addEventListener('blur', () => {
      this.inputStatus = 'blur'
    })

    this.appDom.addEventListener('click', this.handleHideVoipPopover)
  },
  beforeDestroy() {
    this.appDom.removeEventListener('click', this.handleHideVoipPopover)
  },
  methods: {
    canIUse() {
      return new Promise(async (resolve) => {
        const { data } = await getStudentCallManage()

        if (!data) {
          resolve(false)
          return
        }

        // callManageUsableVO 可用时段 callManageLimitVO 特殊限制
        const {
          callManageUsableVO: callManageUsable = [],
          callManageLimitVO: callManageLimit = []
        } = data

        const getToday = () => {
          const today = '日一二三四五六'.charAt(new Date().getDay())

          switch (today) {
            case '日':
              return 7
            case '一':
              return 1
            case '二':
              return 2
            case '三':
              return 3
            case '四':
              return 4
            case '五':
              return 5
            case '六':
              return 6
            default:
              return
          }
        }

        // 存在特殊限制
        if (callManageLimit.length) {
          const limit = callManageLimit.find((i) => {
            const { startTime, endTime } = i
            const nowTime = new Date().getTime()
            if (
              nowTime >= new Date(startTime).getTime() &&
              nowTime <= new Date(endTime).getTime()
            ) {
              return true
            } else {
              return false
            }
          })

          if (limit) {
            const { startTime, endTime } = limit
            this.$popup.show({
              type: 'alert',
              success: (popup) => {
                popup.$on('confirm', () => {
                  this.$popup.hide('alert')
                })
                popup.setData({
                  content: `当前处于禁用时段，禁用时间为${startTime}至${endTime}`
                })
              }
            })
            resolve(false)
            return
          }
        }

        // 存在可用时段
        if (callManageUsable.length) {
          const usableArr = callManageUsable.filter((i) => i.week == getToday())
          const nowTime = new Date().getTime()

          const canUse = usableArr.some((i) => {
            const { startTime, endTime } = i

            if (
              nowTime >=
                new Date(
                  `${this.$utils.parseTime(nowTime, '{y}-{m}-{d}')} ${startTime}`
                ).getTime() &&
              nowTime <=
                new Date(`${this.$utils.parseTime(nowTime, '{y}-{m}-{d}')} ${endTime}`).getTime()
            ) {
              return true
            } else {
              return false
            }
          })

          if (canUse) {
            resolve(true)
            return
          } else {
            const getCanUseTime = () => {
              const strArr = callManageUsable.map((i, index) => {
                const { startTime, endTime, week } = i

                if (index === callManageUsable.length - 1) {
                  return `周${'一二三四五六日'.charAt(week - 1)} ${startTime}~${endTime}`
                }

                const { startTime: startTimeNext } = callManageUsable[index + 1]

                if (startTime != startTimeNext) {
                  return `周${'一二三四五六日'.charAt(week - 1)} ${startTime}~${endTime}`
                }

                return `周${'一二三四五六日'.charAt(week - 1)}`
              })
              return strArr.join(',')
            }
            this.$popup.show({
              type: 'alert',
              success: (popup) => {
                popup.$on('confirm', () => {
                  this.$popup.hide('alert')
                })
                popup.setData({
                  content: `可用时间段为：${getCanUseTime()}`
                })
              }
            })
            resolve(false)
            return
          }
        }

        resolve(true)
      })
    },
    changeMessageType() {
      switch (this.messageType) {
        case MessageType.TEXT:
          this.messageType = MessageType.VOICE
          break
        case MessageType.VOICE:
          this.messageType = MessageType.TEXT
          break
        default:
          break
      }
    },
    handlerH5RecorderSuccess(res) {
      const { data, duration, localUrl } = res

      if (parseInt(duration) === 0) {
        this.$message.error({
          message: '语音时间小于1秒',
          offset: 20
        })
        return
      }

      const date = Date.now()
      const file = new File([data], `${date}.mp3`, {
        type: 'audio/mpeg',
        lastModified: Date.now()
      })

      this.sendVoiceMessage(file)
    },
    handlerH5RecorderError(code) {
      switch (code) {
        case '101':
          this.$message.error('当前浏览器版本较低，请更换浏览器使用，推荐在微信中打开。')
          break
        case '201':
          this.$message.error('麦克风权限被拒绝，请刷新页面后授权麦克风权限。')
          break
        default:
          this.$message.error('未知错误，请刷新页面重试')
          break
      }
    },
    startRecorder() {
      this.$refs.recorderRef.start()
      this.isRecording = true
      this.$emit('change', true)
    },
    endRecorder() {
      this.$refs.recorderRef.stop()
      this.isRecording = false
      this.$emit('change', false)
    },
    async sendTextMessage() {
      if (!(await this.canIUse())) return

      if (!this.draft.text) return

      const { userId: targetId } = this.currentContact
      this.$im.sendTextMessage(targetId, this.draft.text, (res) => {
        if (res === 0) {
          this.draft.text = ''
        }
      })
    },
    async sendVoiceMessage(file, duration) {
      if (!(await this.canIUse())) return

      const { userId: targetId } = this.currentContact

      this.$im.sendVoiceMessage(targetId, file, duration, (res) => {
        console.log('sendVoiceMessage =>', res)
      })
    },
    async toCall(type) {
      this.handleHideVoipPopover()

      if (!(await this.canIUse())) return

      const { userId: targetId, userInfo } = this.currentContact
      const callerId = this.serialNo
      const { name: callerName } = this.studentInfo
      const listenerId = userInfo.miniOpenid
      const listenerName = `${callerName}家长`
      const params = window.android
        ? {
            targetId,
            roomType: type, // 通话类型
            callerId, // 拨打方id
            callerName, // 显示的拨打方名字，设备端发起通话时无效
            listenerId, // 接听方id
            listenerName // 显示的接听方名字
          }
        : targetId

      this.$im.call(params, (success) => {
        if (success) {
          this.$popup.show({
            type: 'calling',
            success: (popup) => {
              popup.setData({
                type: 'active',
                data: userInfo
              })
            }
          })
        }
      })
    },
    handleHideVoipPopover() {
      this.isShowVoipPopover = false
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  height: 81px;

  .item {
    width: 30px;
    height: 30px;
  }

  .input {
    font-size: 18px;
    border-radius: 8px;
    border: none;
  }

  .btn-confirm {
    width: 80px;
    font-size: 18px;
    border-radius: 8px;
  }

  .dialog-recording {
    left: calc(50%);
    top: -130px;
    transform: translateX(-50%);

    .wrap {
      padding: 0 0 0 80px;

      .icon-recording {
        width: 203px;
        height: 75px;
      }

      .icon-cancel {
        width: 30px;
        height: 30px;
      }
    }
  }
}
</style>
